import {
  reqAddOrUpdateAttrValue,
  reqAttrList,
  reqCategory1List,
  reqCategory2List,
  reqCategory3List,
  reqDelAttr,
} from '@/api/product/attr';
import {
  attrItem,
  attrListType,
  attrValueItem,
  attrValueListType,
  EditableRowProps,
  EditableCellProps,
  categoryList,
} from '@/api/product/model/attrTypes';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Card,
  Form,
  Input,
  InputRef,
  message,
  Popconfirm,
  Select,
  Table,
  Tag,
  Tooltip,
} from 'antd';
import { useForm } from 'antd/lib/form/Form';
import { ColumnsType } from 'antd/lib/table';
import React, { useEffect, useState, useRef, useContext } from 'react';
import type { FormInstance } from 'antd/es/form';

const { Option } = Select;
type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

export default function Attr() {
  // 平台属性三级分类相关数据及方法---------start
  const [form1] = useForm();
  const [category1List, setCategory1List] = useState<categoryList>([]);
  const [category1Id, setcategory1Id] = useState<number>();
  const [category2List, setCategory2List] = useState<categoryList>([]);
  const [category2Id, setcategory2Id] = useState<number>();
  const [category3List, setCategory3List] = useState<categoryList>([]);
  const [category3Id, setcategory3Id] = useState<number>();
  const [updateId, setUpdateId] = useState<number>();
  // 初始化获取一级分类列表
  useEffect(() => {
    const getCategory1List = async () => {
      const category1List = await reqCategory1List();
      setCategory1List(category1List);
    };
    getCategory1List();
  }, []);

  const handleCategory1Change = async () => {
    form1.resetFields(['category2', 'category3']); // 清除二三级分类
    setCategory3List([]);
    //  获取并设置category1List
    const category1List = await reqCategory1List();
    setCategory1List(category1List);
    // 获取二级分类
    const category1Id = form1.getFieldValue('category1');
    setcategory1Id(category1Id);
    const category2List = await reqCategory2List(category1Id as number);
    setCategory2List(category2List);
  };
  const handleCategory2Change = async () => {
    form1.resetFields(['category3']); // 清除三级分类
    //  获取并设置category1List
    const category2List = await reqCategory2List(category1Id as number);
    setCategory2List(category2List);
    // 获取三级分类
    const category2Id = form1.getFieldValue('category2');
    setcategory2Id(category2Id);
    const category3List = await reqCategory3List(category2Id as number);
    setCategory3List(category3List);
  };
  const handleCategory3Change = async () => {
    //  获取并设置category1List
    const category3List = await reqCategory3List(category2Id as number);
    setCategory3List(category3List);
    // 设置category3Id
    const category3Id = form1.getFieldValue('category3');
    setcategory3Id(category3Id);
  };
  // 平台属性三级分类相关数据及方法---------end

  // 平台属性表格相关属性及方法------start
  const [loading, setLoading] = useState(false);
  const [attrList, setAttrList] = useState<attrListType>([]);

  const columns: ColumnsType<attrItem> = [
    // 指定每一行的数据对象的类型
    {
      title: '序号',
      dataIndex: 'id',
      render(value, row, index) {
        // console.log('render', value, row, index)
        return index + 1;
      },
      fixed: 'left',
      width: 100, // 宽度
      align: 'center', // 水平居中
    },

    {
      title: '属性名称',
      dataIndex: 'attrName',
    },

    {
      title: '属性值列表',
      dataIndex: 'attrValueList',
      render: (_, { attrValueList }) => (
        <>
          {attrValueList.map((attrval) => {
            return (
              <Tag color="success" key={attrval.id}>
                {attrval.valueName}
              </Tag>
            );
          })}
        </>
      ),
    },

    {
      title: '操作',
      render: (value, row, index) => {
        return (
          <>
            {/* 必须要一个根标签 */}
            <Tooltip placement="top" title="修改属性">
              <Button
                type="primary"
                icon={<EditOutlined />}
                onClick={() => updateTM(row)}
              ></Button>
            </Tooltip>
            <Tooltip placement="top" title="删除属性">
              <Popconfirm
                title={`确定删除${row.attrName}吗?`}
                okText="确定"
                cancelText="取消"
                onConfirm={() => DelTM(row)}
              >
                <Button
                  type="primary"
                  danger
                  icon={<DeleteOutlined />}
                  className="ml"
                />
              </Popconfirm>
            </Tooltip>
          </>
        );
      },
      fixed: 'right', // 固定在右侧
      width: 120, // 指定宽度
    },
  ];

  // 获取平台属性列表
  const getAttrList = async () => {
    if (category3Id) {
      setLoading(true);
      let attrList = await reqAttrList(
        category1Id as number,
        category2Id as number,
        category3Id
      );
      setLoading(false);
      setAttrList(attrList);
    }
  };
  // 初始化获取平台属性列表
  useEffect(() => {
    getAttrList();
  }, [category3Id]);

  const [isAddAttrCard, setIsAddAttrCard] = useState(false); //控制新增或修改属性值卡片的展示
  // 添加平台属性
  const addAttr = () => {
    // console.log(category3Id, 'category3Id');
    // 清除之前新增的属性
    form2.resetFields();
    setAttrValueList([]);
    // 展示新增卡片
    setIsAddAttrCard(true);

    // 添加属性没有id，要清空id
    setUpdateId(undefined);

    // 修改key对应的count
    setCount(attrValueList.length);

    // 清空attrname,保证添加属性的时候新增属性值按钮为不可选状态
    setAttrName('');
  };

  // 关闭新增属性值卡片
  const closeAddCard = () => {
    setIsAddAttrCard(false);
  };
  // 更新属性值
  const updateTM = (row: attrItem) => {
    setUpdateId(row.id);
    setAttrName(row.attrName);
    // console.log(row.id, 'row.id');
    form2.setFieldsValue(row); //属性名回填
    // console.log(row.attrValueList, 'row.attrValueList');
    // setCount(row.attrValueList.length)
    // console.log(row.attrValueList.length - 1, 'row.attrValueList.length');
    let index = count;
    // console.log(count, 'count');
    const res = row.attrValueList.map((item) => {
      return {
        key: index++,
        ...item,
      };
    });
    // console.log(res, 'res');

    // const hasKey=row.attrValueList.concat()
    setAttrValueList(row.attrValueList); //属性值的回填

    setIsAddAttrCard(true);
  };
  // 删除属性
  const DelTM = async (row: attrItem) => {
    await reqDelAttr(row.id as number);
    getAttrList();
  };
  // 平台属性表格相关属性及方法------end

  // 添加或更新平台属性卡片的相关数据和方法--------start
  const [form2] = useForm();
  const [count, setCount] = useState(0);
  const [attrName, setAttrName] = useState(''); //属性名
  const [attrValueList, setAttrValueList] = useState<attrValueListType>([
    {
      key: 0,
      id: undefined,
      valueName: '',
      attrId: undefined,
    },
  ]); //属性值列表

  // 点击取消底部取消按钮
  const cancel = () => {
    setCount(0);
    closeAddCard();
  };

  // 获取属性名
  const getAttrName = (event: any) => {
    setAttrName(event.target.value);
  };
  // 点击保存按钮新增或更新平台属性
  const BottomSave = async () => {
    try {
      // console.log(updateId, 'updateId');
      if (updateId) {
        await reqAddOrUpdateAttrValue({
          id: updateId,
          attrName: attrName,
          attrValueList: attrValueList, // 属性值列表
          categoryId: category3Id as number,
          categoryLevel: 3,
        });
        message.success('修改成功');
      } else {
        //  新增属性
        await reqAddOrUpdateAttrValue({
          attrName: attrName,
          attrValueList: attrValueList, // 属性值列表
          categoryId: category3Id as number,
          categoryLevel: 3,
        });
        message.success('新增成功');
      }

      // 关闭标签
      closeAddCard();
      // 重新获取属性列表
      getAttrList();
      // 重置count
      setCount(0);
    } catch (error) {
      message.error('保存失败');
    }
  };
  // 新增属性值按钮
  const handleAdd = () => {
    // console.log(attrValueList, 'attrValueList');

    const newData: attrValueItem = {
      key: count,
      id: undefined,
      valueName: '请输入属性值名称',
      attrId: undefined,
    };
    setAttrValueList([...attrValueList, newData]);
    // console.log(count, 'handleAdd');

    setCount(count + 1);
  };

  // components中的row
  const EditableContext = React.createContext<FormInstance<any> | null>(null);
  const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };

  // components中的cell
  const EditableCell: React.FC<EditableCellProps> = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef<InputRef>(null);
    const form = useContext(EditableContext)!;

    useEffect(() => {
      if (editing) {
        inputRef.current!.focus();
      }
    }, [editing]);

    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    };

    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({ ...record, ...values });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };

    let childNode = children;

    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{ margin: 0 }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title}不能为空`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{ paddingRight: 24 }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }

    return <td {...restProps}>{childNode}</td>;
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  //点击删除属性值
  const handleDelete = (row: attrValueItem) => {
    // console.log(row, 'row');
    // console.log(attrValueList, 'attrValueList');

    // 点击新增属性生成的行有key,已经有的属性没key
    if (row.key) {
      const newData = attrValueList.filter((item) => item.key !== row.key);
      setAttrValueList(newData);
    }
    if (row.id) {
      const newData = attrValueList.filter((item) => item.id !== row.id);
      setAttrValueList(newData);
    }
  };
  const handleSave = (row: attrValueItem) => {
    const newData = [...attrValueList];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setAttrValueList(newData);
  };
  const defaultColumns: (ColumnTypes[number] & {
    editable?: boolean;
    dataIndex: string;
  })[] = [
    {
      title: '序号',
      dataIndex: 'id',
      render(value, row, index) {
        // console.log('render', value, row, index)
        return index + 1;
      },
      fixed: 'left',
      width: 100, // 宽度
      align: 'center', // 水平居中
    },

    {
      title: '属性值名称',
      dataIndex: 'valueName',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (data: any, record: any) =>
        attrValueList.length >= 1 ? (
          <Popconfirm
            title="确定删除吗?"
            onConfirm={() => handleDelete(record)}
          >
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              className="ml"
            />
          </Popconfirm>
        ) : null,
    },
  ];
  const columns2 = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: attrValueItem) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  // 设置新增卡片tabel的key值
  const setKey = (record: any) => {
    if (record.key) {
      return record.key;
    } else if (record.id) {
      return record.id;
    } else {
      // console.log('没有key也没id ');
      return -1;
    }
  };
  // 添加或更新平台属性卡片的相关数据和方法------end
  return (
    <>
      {/* 三级列表 */}
      <Card style={{ margin: 20 }}>
        <Form form={form1} layout="inline">
          <Form.Item
            name="category1"
            style={{ marginBottom: 20 }}
            label="一级分类"
          >
            <Select
              placeholder="请选择"
              style={{ width: 200 }}
              onChange={handleCategory1Change}
            >
              {category1List.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="category2"
            style={{ marginBottom: 20 }}
            label="二级分类"
          >
            <Select
              placeholder="请选择"
              style={{ width: 200 }}
              onChange={handleCategory2Change}
            >
              {category2List.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="category3"
            style={{ marginBottom: 20 }}
            label="三级分类"
          >
            <Select
              placeholder="请选择"
              style={{ width: 200 }}
              onChange={handleCategory3Change}
            >
              {category3List.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Card>

      {/*  控制新增或修改属性值卡片的展示*/}
      {isAddAttrCard ? (
        // 新增或修改属性值卡片
        <Card style={{ margin: 20 }}>
          <Form form={form2} layout="inline">
            <Form.Item
              name="attrName"
              style={{ marginBottom: 20 }}
              label="属性名"
            >
              <Input onChange={getAttrName} value={attrName}></Input>
            </Form.Item>
          </Form>
          <div>
            <Button
              onClick={handleAdd}
              type="primary"
              style={{ marginBottom: 16 }}
              disabled={!attrName}
            >
              新增属性值
            </Button>
            <Button
              type="default"
              style={{ marginBottom: 16, marginLeft: 10 }}
              onClick={closeAddCard}
            >
              取消
            </Button>
          </div>
          <Table
            components={components}
            rowClassName={() => 'editable-row'}
            bordered
            dataSource={attrValueList}
            columns={columns2 as ColumnTypes}
            pagination={false}
            style={{ marginBottom: 16 }}
            rowKey={setKey}
          />
          <div>
            <Button
              type="primary"
              style={{ marginBottom: 10 }}
              onClick={BottomSave}
            >
              保存
            </Button>
            <Button
              type="default"
              style={{ marginBottom: 10, marginLeft: 10 }}
              onClick={cancel}
            >
              取消
            </Button>
          </div>
        </Card>
      ) : (
        // 展示平台属性卡片
        <Card style={{ margin: 20 }}>
          <div>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={addAttr}
              style={{ marginBottom: 10 }}
              disabled={!category3Id}
            >
              添加
            </Button>
          </div>
          <Table
            bordered
            loading={loading}
            dataSource={attrList}
            columns={columns}
            pagination={false}
            rowKey="id"
          ></Table>
        </Card>
      )}
    </>
  );
}
